package com.hpin.mlxteacher.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.ChatListAdapter;
import com.hpin.mlxteacher.base.BaseFragment;
import com.hpin.mlxteacher.bean.MessageBean;
import com.hpin.mlxteacher.chat.ChatActivity;
import com.hpin.mlxteacher.chat.ChooseGroupNumsActivity;
import com.hpin.mlxteacher.chat.ContractsActivity;
import com.hpin.mlxteacher.chat.SearchContractActivity;
import com.hpin.mlxteacher.db.DatabaseManager;
import com.hpin.mlxteacher.swipe.SwipeMenu;
import com.hpin.mlxteacher.swipe.SwipeMenuCreator;
import com.hpin.mlxteacher.swipe.SwipeMenuItem;
import com.hpin.mlxteacher.swipe.SwipeMenuListView;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.LogUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 聊天的fragment
 * Created by Aaron on 16/2/29.
 */
public class ChatFragment extends BaseFragment implements View.OnClickListener {
    //    private ImageView iv_left;
    private ImageView iv_right;
    private SwipeMenuListView rv_contact;
    private Intent mIntent;
    private ChatListAdapter adapter;
    private List<MessageBean> chatList = new ArrayList<>();
    private PopupWindow chatPup;
    //    private MessageBean newChat;
    private String chatTopic;//当前聊天的topic

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_chat, null);

        initWidget(view);
        //注册EventBus
        EventBus.getDefault().register(this);

        return view;
    }

    /**
     * 查询数据库 获取最近的聊天列表
     */
    private class QueryTask extends AsyncTask<String, Integer, List<MessageBean>> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected List<MessageBean> doInBackground(String... params) {

            try {
                return DatabaseManager.getInstance().getChatListFromTopics(getActivity(), sp.getString(Constant.phoneNum, ""));
            } catch (Exception e) {
                e.printStackTrace();
                showToast("查询聊天记录失败");
                return null;
            }

        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(List<MessageBean> result) {

//            LogUtil.e("tag", "查询到的聊天个数:" + result.size());

            //填充adapter 数据
            chatList = result;
            adapter.setData(chatList);
            adapter.notifyDataSetChanged();

        }

    }

    /**
     * 收到了消息,通知页面发生改变
     *
     * @param mb
     */
    public void onEventMainThread(MessageBean mb) {

//        LogUtil.e("tag",  getClass().getName() + " 新消息到达: ");

        if (chatList == null)
            return;

        switch (mb.operationStyle) {

            case Constant.OFF_GROUP://退出群, 删除好友的 广播,在列表中删除该聊天的item

                exitGroup(mb);

                break;

            case Constant.RECEIVE_MESSAGE://接受到新的消息 (自己发的消息也会在这里调用)

                receiveMsg(mb);

                break;

            case Constant.DELETE_RECENT_HISTORY://删除最近聊天记录

                //迭代集合,找到该条目
                for (Iterator<MessageBean> it = chatList.iterator(); it.hasNext(); ) {
                    MessageBean msb = it.next();
                    if (msb.channelId != null && msb.channelId.equals(mb.channelId)) {

                        chatList.remove(msb);
                        mb.sendDate = msb.sendDate;
                        chatList.add(0, mb);

                        if (adapter != null)
                            adapter.notifyDataSetChanged();

                        return;
                    }
                }

                //列表中没有该聊天列表,增加该条目
                chatList.add(0, mb);//在0的位置上添加该聊天记录

                if (adapter != null)
                    adapter.notifyDataSetChanged();

                break;

        }

    }

    /**
     * 接受到了新消息
     *
     * @param mb
     */
    private void receiveMsg(MessageBean mb) {
        //                LogUtil.e("tag", "fragment 页面里 mb的值: " + mb.content);

//        //当前正在聊天的topic 未读消息设置为0
//        if (mb.channelId.equals(chatTopic))
//            mb.unreadCount = 0;

        //迭代看最近聊天列表中是否有该聊天的item
        for (Iterator<MessageBean> it = chatList.iterator(); it.hasNext(); ) {
            MessageBean msb = it.next();
            if (msb.channelId != null && msb.channelId.equals(mb.channelId)) {
//                        it.remove();
                chatList.remove(msb);

                LogUtil.e("tag", " =====   未读条数   ==== :" + mb.isRead);

                chatList.add(0, mb);
                if (adapter != null)
                    adapter.notifyDataSetChanged();

                return;
            }
        }

        //列表中没有该聊天列表,增加该条目
        chatList.add(0, mb);//在0的位置上添加该聊天记录

        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    /**
     * 进入聊天页面
     *
     * @param mb
     */
    private void enterChat(MessageBean mb) {
        mIntent = new Intent(getActivity(), ChatActivity.class);
        //判断最后一条信息的发送者是谁, 如果是本人则不处理, 如果是对方, 则把receive的信息改为对方的
                /*
                   mb.channelId = contact.channelId;//聊天的topic
        mb.receiveName = contact.receiveName;//聊天的名称, 单聊就为聊天对象的昵称, 群聊为群聊昵称
        mb.receiveId = contact.receiveId;//聊天对象的id
        mb.receivePic = contact.receivePic;//聊天对象的头像
                 */
        //单聊 和 跟系统聊天
        if (mb.channelId.startsWith(Constant.START_SINGLE) || mb.channelId.startsWith(Constant.START_S))

            if (!sp.getString(Constant.phoneNum, "").equals(mb.sendId)) { //私聊的时候发送者为对方
                mb.receiveName = mb.sendName;
                mb.receiveId = mb.sendId;
                mb.receivePic = mb.sendPic;
            }

        mIntent.putExtra("contact", mb);
        startActivity(mIntent);

        mb.isRead = 0;
        adapter.notifyDataSetChanged();
        chatTopic = mb.channelId; //当前聊天的topic

    }

    /**
     * 退出群, 删除好友
     *
     * @param mb
     */
    private void exitGroup(MessageBean mb) {
        //退出群的 广播
        for (Iterator<MessageBean> it = chatList.iterator(); it.hasNext(); ) {
            MessageBean cb = it.next();
            if (mb.channelId.equals(cb.channelId)) {
//                        chatList.remove(cb);
                it.remove();
            }
        }

        if (adapter != null)
            adapter.notifyDataSetChanged();

    }

    @Override
    public void onResume() {
        super.onResume();
        chatTopic = "";//当天聊天对象 置为空

        //查询topic表,设置最近聊天列表
        if (getActivity() != null)
            new QueryTask().execute();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        LogUtil.e("tag", "==== ondestory ====");
        //反注册EventBus
        EventBus.getDefault().unregister(this);

    }

    private void initWidget(View view) {

        iv_right = (ImageView) view.findViewById(R.id.iv_right);

        rv_contact = (SwipeMenuListView) view.findViewById(R.id.rv_contact);

        if (getActivity() != null) {
            adapter = new ChatListAdapter(getActivity(), chatList);
            rv_contact.setAdapter(adapter);
        }
//        //使RecyclerView保持固定的大小,这样会提高RecyclerView的性能。
//        rv_contact.setHasFixedSize(true);
//        //如果你需要显示的是横向滚动的列表或者竖直滚动的列表，则使用这个LayoutManager。
//        // 显然，我们要实现的是ListView的效果，所以需要使用它。
//        // 生成这个LinearLayoutManager之后可以设置他滚动的方向，默认竖直滚动，所以这里没有显式地设置。
//        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
////      rv_contact.setLayoutManager(new GridLayoutManager(this, 2));//这里用线性宫格显示 类似于grid view
////      rv_contact.setLayoutManager(new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL));//这里用线性宫格显示 类似于瀑布流
//
//        rv_contact.setLayoutManager(layoutManager);
//
//        rv_contact.addItemDecoration(new DividerItemDecoration(getActivity(),
//                DividerItemDecoration.VERTICAL_LIST));

        rv_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (chatList != null && chatList.size() > 0) {

                    enterChat(chatList.get(position));

                }
            }

        });

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
//                deleteItem.setBackground(getResources().getColor(R.color.red));
                // set item width
                deleteItem.setWidth(DensityUtil.dip2px(getActivity(), 80));
                // set item title
//                deleteItem.setTitle("删除");
//                deleteItem.setTitleSize(15);
//                deleteItem.setTitleColor(Color.WHITE);
//                // set a icon
                deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);

            }
        };

        rv_contact.setMenuCreator(creator);

        rv_contact.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        // 删除
                        new AlertDialog.Builder(getActivity()).setMessage("删除后将会清空聊天记录")
                                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

//                                        //列表中删除该条目, 清空该topic的历史聊天记录
                                        deleteItem(position);

                                    }
                                }).setNegativeButton("取消", null).show();

                        break;
                }
                return false;
            }
        });

        iv_right.setOnClickListener(this);
    }

    /**
     * 列表中删除该条目, 清空该topic的历史聊天记录
     *
     * @param position
     */
    private void deleteItem(final int position) {
        if (chatList == null || chatList.size() < 1)
            return;

        final String topic = chatList.get(position).channelId;

        chatList.remove(position);

        adapter.setData(chatList);
        adapter.notifyDataSetChanged();

        new Thread(new Runnable() {
            @Override
            public void run() {

                DatabaseManager.getInstance().deleteHistory(getActivity(), topic, sp.getString(Constant.phoneNum, ""));
                DatabaseManager.getInstance().deleteTopic(getActivity(), topic, sp.getString(Constant.phoneNum, ""));

                EventBus.getDefault().post(Constant.UPDATE_RED_COUNT);

            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_right:

                moreContact(v);

                break;

            case R.id.tv_contract://通讯录

                dismissPup();

                mIntent = new Intent(getActivity(), ContractsActivity.class);
                startActivity(mIntent);

                break;

            case R.id.tv_group://发起群聊

                dismissPup();

                mIntent = new Intent(getActivity(), ChooseGroupNumsActivity.class);
                mIntent.putExtra("style", Constant.CREATE_GROUP);
                startActivity(mIntent);

                break;

            case R.id.tv_add_contract://添加好友

                dismissPup();

                mIntent = new Intent(getActivity(), SearchContractActivity.class);
                startActivity(mIntent);

                break;

        }
    }

    /**
     * 消失poup
     */
    private void dismissPup() {
        if (chatPup != null && chatPup.isShowing())
            chatPup.dismiss();
    }

    private void moreContact(View v) {

        View popuView = View.inflate(getActivity(), R.layout.popup_more_contract, null);

        chatPup = new PopupWindow(popuView,
                DensityUtil.dip2px(getActivity(), 120), ViewGroup.LayoutParams.WRAP_CONTENT);
//        chatPup.setContentView(popuView);
        chatPup.setOutsideTouchable(true);
        chatPup.setFocusable(true);
        chatPup.setBackgroundDrawable(new BitmapDrawable());
        //x y   DensityUtil.dip2px(getActivity(), 5)
        chatPup.showAsDropDown(v, 0, 0);

        TextView tv_contract = (TextView) popuView.findViewById(R.id.tv_contract);
        TextView tv_group = (TextView) popuView.findViewById(R.id.tv_group);
        TextView tv_add_contract = (TextView) popuView.findViewById(R.id.tv_add_contract);

        tv_contract.setOnClickListener(this);
        tv_group.setOnClickListener(this);
        tv_add_contract.setOnClickListener(this);

    }
}
